//
//  YunCangViewController.swift
//  Wmsmobile
//
//  Created by wangshuning on 16/7/19.
//  Copyright © 2016年 Nick xu. All rights reserved.
//

import UIKit

import SVProgressHUD

let  YunCangCollectionSpace:CGFloat = 10

class YunCangViewController: UICollectionViewController,YunCangViewModelDelegate,UICollectionViewDelegateFlowLayout,mainMenuSlideViewDelegate {
    
    var viewModel:YunCangViewModel?
    
    init(){
        
        //创建flowLayout
        let flowLayout = UICollectionViewFlowLayout()
        
        let width = (KscreenWidth - 5 * YunCangCollectionSpace) / 4
        flowLayout.itemSize = CGSizeMake(width, width)
        flowLayout.minimumLineSpacing = YunCangCollectionSpace
        flowLayout.minimumInteritemSpacing = YunCangCollectionSpace
        flowLayout.headerReferenceSize = CGSizeMake(KscreenWidth, 60)
        
        super.init(collectionViewLayout: flowLayout)
        viewModel = YunCangViewModel()
        viewModel?.delegate = self
        
        
        self.collectionView?.registerClass(YunCangViewCellCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        self.collectionView?.registerClass(MainMenuSectionHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
        let headView = mainMenuSlideView(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
        headView.delegate = self
        self.navigationItem.titleView = headView
        
        //设置消息item
        let rightItem:UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "xiaoxi"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(YunCangViewController.didclickXiaoxi))
        self.navigationItem.rightBarButtonItem = rightItem
    }
    
    //备用构造方法
    private override init(collectionViewLayout layout: UICollectionViewLayout) {
        //创建flowLayout
        super.init(collectionViewLayout: layout)
        viewModel = YunCangViewModel()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.collectionView!.backgroundColor = UIColor.whiteColor()
        viewModel?.updateData(String(format: "%d", OriginalID))
    }
    
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let model:YunCangModel = (self.viewModel?.activeArray![indexPath.row])! as! YunCangModel
        if model.FGID == NSNumber(integer: rootID) {
            
            return
        }
        //判断如果是查询货位，push出HWMSDViewController控制器
        if model.FCAPTION == "查询货位" {
//            self.presentViewController(HWMSDViewController(), animated: true, completion: nil)
            self.navigationController?.pushViewController(HWMSDViewController(), animated: true)
            return
        }
        //判断如果是查询货品，push出HWMSDViewController控制器
        if model.FCAPTION == "查询货品" {
            //            self.presentViewController(HWMSDViewController(), animated: true, completion: nil)
            self.navigationController?.pushViewController(UIViewController(), animated: true)
            return
        }
        //判断如果是查询货品，push出HWMSDViewController控制器
        if model.FCAPTION == "容器拣货" {
            //            self.presentViewController(HWMSDViewController(), animated: true, completion: nil)
//            let path:UIStoryboard = NSBundle.mainBundle().pathForResource("mainMenu.storyboard", ofType: nil) as! UIStoryboard
            let sb = UIStoryboard(name: "mainMenu", bundle: nil)
            self.navigationController?.pushViewController(sb.instantiateViewControllerWithIdentifier("containerPick"), animated: true)
            return
        }
        self.viewModel?.updateData(String(format: "%@", arguments: [model.FGID!]))
        collectionView.cellForItemAtIndexPath(indexPath)?.selected = false
    }
    
    //MARK: - delegate
    func didclickXiaoxi() -> () {
        let xiaoxiVC = YCXiaoxiViewcontroller()
        self.navigationController?.pushViewController(xiaoxiVC, animated: true)
    }
    func didClickButton(button: UIButton) {
        //切换数据源
        self.viewModel?.activeArray = button.titleForState(UIControlState.Normal) == "常用" ? self.viewModel?.ArrayCommenUse : self.viewModel?.ArrayMenuData
        self.collectionView?.reloadData()
    }
    
    func updateDatasource(array: NSArray) {
        if array.count == 0{
            dispatch_async(dispatch_get_main_queue(), { 
                
                SVProgressHUD.showInfoWithStatus("功能待完善")
            })
            return
        }
        self.collectionView?.reloadData()
    }
}
//MARK: - datasource
extension YunCangViewController{
    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 5
    }
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (self.viewModel?.activeArray?.count) ?? 0
    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let model:YunCangModel = (self.viewModel?.activeArray![indexPath.row])! as! YunCangModel
        let cell:YunCangViewCellCollectionViewCell = (collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as? YunCangViewCellCollectionViewCell)!
        cell.model = model
        cell.backgroundColor = UIColor.hexStringToUIColor("#6A5ACD")
        cell.ColorSolution = indexPath.item % 2 == 1
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        let header:MainMenuSectionHeaderView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "header", forIndexPath: indexPath) as! MainMenuSectionHeaderView
        return header
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(0, YunCangCollectionSpace, 0, YunCangCollectionSpace)
    }
  
}




//MARK: - 头部自定义选择器view
protocol mainMenuSlideViewDelegate:NSObjectProtocol{
    func didClickButton(button:UIButton)
}


class mainMenuSlideView:UIView {
    
    var activeButton:UIButton?
    
    let indectorViewHeight:CGFloat = 3
    
//    init(){
//        super.init(frame: <#T##CGRect#>)
//    }
    weak var delegate:mainMenuSlideViewDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(leftButton)
        self.addSubview(rightButton)
        self.addSubview(indectorView)
        self.leftButton.frame = CGRectMake(0, 0, frame.size.width / 2, frame.size.height - indectorViewHeight)
        self.rightButton.frame = CGRectMake(frame.size.width / 2, 0, frame.size.width / 2, frame.size.height - indectorViewHeight)
        self.indectorView.frame = CGRectMake(self.leftButton.centerX - 40, frame.size.height - indectorViewHeight,80 , indectorViewHeight)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func clickButton(button:UIButton){
        if activeButton == button {
            return
        }
        activeButton = button
        if self.delegate != nil{
            self.delegate?.didClickButton(button)
        }
        //移动指示器
        UIView.animateWithDuration(0.5) { 
            self.indectorView.centerX = button.titleForState(UIControlState.Normal) == "常用" ? self.rightButton.centerX : self.leftButton.centerX
        }
    }
    
    
    
    lazy private var leftButton:UIButton = {
        let bt = UIButton()
        bt.setTitle("菜单", forState: UIControlState.Normal)
        bt.addTarget(self, action:#selector(mainMenuSlideView.clickButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        return bt
    }()
    lazy private var rightButton:UIButton = {
        let bt = UIButton()
        bt.setTitle("常用", forState: UIControlState.Normal)
        bt.addTarget(self, action:#selector(mainMenuSlideView.clickButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        return bt
    }()
    lazy private var indectorView:UIView = {
        let temp = UIView()
        temp.backgroundColor = UIColor.darkGrayColor()
        return temp
    }()



}












